<template>
  <div class="book-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">图书列表</h1>
          <p class="page-subtitle">浏览和搜索图书信息</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ totalBooks }}</span>
            <span class="stat-label">总图书</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ availableBooks }}</span>
            <span class="stat-label">可借阅</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="书名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入书名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="作者">
          <el-input
            v-model="searchForm.author"
            placeholder="请输入作者"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="可借阅" :value="0" />
            <el-option label="已借出" :value="1" />
            <el-option label="维修中" :value="2" />
            <el-option label="已下架" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBooks">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图书列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h3>图书列表 ({{ books.length }}本图书)</h3>
          <div>
            <span style="margin-right: 10px; color: #666;">加载状态: {{ loading ? '加载中' : '已完成' }}</span>
            <el-button type="primary" @click="refreshBooks">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>



      <el-table
        v-loading="loading"
        :data="books"
        stripe
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#fafafa', color: '#262626' }"
      >
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column label="封面" width="100" align="center">
          <template #default>
            <div class="book-cover">
              <el-icon><Reading /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="书名" min-width="200" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="150" show-overflow-tooltip />
        <el-table-column prop="isbn" label="ISBN" width="150" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              :class="getStatusClass(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" align="center">
          <template #default="{ row }">
            <span class="stock-info">{{ row.available || 0 }}/{{ row.total || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="canBorrow(row)"
              type="primary"
              size="small"
              @click="borrowBook(row)"
            >
              立即借阅
            </el-button>
            <el-button
              v-else
              type="info"
              size="small"
              disabled
            >
              {{ getButtonText(row.status) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 借阅对话框 -->
    <BorrowDialog
      v-model:visible="borrowDialogVisible"
      :book="selectedBook"
      @success="handleBorrowConfirm"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import BorrowDialog from '@/components/BorrowDialog.vue'

const loading = ref(false)
const books = ref([])
const categories = ref([])
const selectedBook = ref(null)
const borrowDialogVisible = ref(false)

const searchForm = ref({
  name: '',
  author: '',
  categoryId: null,
  status: null
})

const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 计算属性
const totalBooks = computed(() => books.value.length)
const availableBooks = computed(() => 
  books.value.filter(book => book.status === 0 && (book.available || 0) > 0).length
)

// 获取图书列表
const fetchBooks = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/books/page', { params })
    if (response.code === 200) {
      const data = response.data
      books.value = data.records || []
      pagination.value.total = data.total || 0

              // 匹配分类名称 - 临时映射方案
        const categoryMapping = {
          1: 105, // 计算机科学 -> 计算机
          2: 100, // 文学小说 -> 文学  
          3: 104, // 历史传记 -> 科技（临时）
          4: 104, // 科学技术 -> 科技
          5: 104, // 经济管理 -> 科技（临时）
          6: 105, // 艺术设计 -> 计算机（临时）
          7: 105, // -> 计算机
          8: 104  // -> 科技
        }
        
        books.value.forEach(book => {
          // 处理分类
          if (book.categoryId) {
            // 使用映射表或直接查找
            const mappedCategoryId = categoryMapping[book.categoryId] || book.categoryId
            const category = categories.value.find(cat => cat.id === mappedCategoryId)
            if (category) {
              book.categoryName = category.name
            } else {
              book.categoryName = '未知分类'
            }
          } else {
            book.categoryName = '无分类'
          }
          

        })
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  }
  loading.value = false
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await request.get('/categories/list')
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索图书
const searchBooks = () => {
  pagination.value.current = 1
  fetchBooks()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    author: '',
    categoryId: null,
    status: null
  }
  pagination.value.current = 1
  fetchBooks()
}

// 刷新图书列表
const refreshBooks = () => {
  fetchBooks()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.size = val
  pagination.value.current = 1
  fetchBooks()
}

const handleCurrentChange = (val) => {
  pagination.value.current = val
  fetchBooks()
}

// 状态相关方法
const getStatusType = (status) => {
  // 兼容数字和字符串类型
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 0: return 'success'
    case 1: return 'warning'
    case 2: return 'info'
    case 3: return 'danger'
    default: return 'info'
  }
}

const getStatusClass = (status) => {
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 0: return 'status-available'
    case 1: return 'status-borrowed'
    case 2: return 'status-maintenance'
    case 3: return 'status-offline'
    default: return ''
  }
}

const getStatusText = (status) => {
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 0: return '可借阅'
    case 1: return '已借出'
    case 2: return '维修中'
    case 3: return '已下架'
    default: return '未知'
  }
}

const getButtonText = (status) => {
  const normalizedStatus = typeof status === 'string' ? parseInt(status) : status
  switch (normalizedStatus) {
    case 1: return '已借出'
    case 2: return '维修中'
    case 3: return '已下架'
    default: return '不可借'
  }
}

const canBorrow = (book) => {
  const normalizedStatus = typeof book.status === 'string' ? parseInt(book.status) : book.status
  return normalizedStatus === 0 && (book.available || 0) > 0
}

// 借阅相关方法
const borrowBook = (book) => {
  selectedBook.value = book
  borrowDialogVisible.value = true
}

const handleBorrowConfirm = () => {
  borrowDialogVisible.value = false
  selectedBook.value = null
  fetchBooks() // 刷新列表
}

onMounted(async () => {
  await fetchCategories() // 先获取分类列表
  fetchBooks() // 再获取图书列表
})
</script>

<style scoped>
.book-list {
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 28px;
  color: #262626;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #595959;
  margin: 0;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 24px;
  border: 1px solid #e8e8e8;
}

.search-form {
  margin: 0;
}

/* 列表卡片 */
.list-card {
  border: 1px solid #e8e8e8;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #262626;
  font-weight: 600;
}

/* 图书封面 */
.book-cover {
  width: 40px;
  height: 56px;
  background-color: #f0f8ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  color: #1890ff;
  font-size: 20px;
}

/* 库存信息 */
.stock-info {
  font-weight: 500;
  color: #262626;
}

/* 状态标签 */
.status-available {
  background-color: #f6ffed !important;
  color: #52c41a !important;
  border-color: #b7eb8f !important;
}

.status-borrowed {
  background-color: #fff2e8 !important;
  color: #faad14 !important;
  border-color: #ffd591 !important;
}

.status-maintenance {
  background-color: #f0f5ff !important;
  color: #1890ff !important;
  border-color: #adc6ff !important;
}

.status-offline {
  background-color: #fff2f0 !important;
  color: #ff4d4f !important;
  border-color: #ffadd2 !important;
}

/* 表格样式 */
.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: 600;
  color: #262626;
}

.el-table td {
  padding: 12px 0;
}

/* 分页 */
.pagination-container {
  margin-top: 24px;
  text-align: center;
}

/* 按钮样式 */
.el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.el-button--primary:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form .el-form-item {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-stats {
    gap: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .stat-number {
    font-size: 20px;
  }
}
</style> 